package com.cxx.home.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cxx.common.dto.UserDto;
import com.cxx.common.entity.Account;
import com.cxx.common.entity.User;
import com.cxx.common.mapper.AccountMapper;
import com.cxx.common.mapper.UserMapper;
import com.cxx.framework.web.CustomException;
import com.cxx.home.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private AccountMapper accountMapper;

    @Override
    public UserDto queryUser(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new CustomException("未查询到该用户");
        }

        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);

        LambdaQueryWrapper<Account> queryWrapper = new LambdaQueryWrapper<>();
        userDto.setAccountName(accountMapper.selectOne(queryWrapper.eq(Account::getUserId, id)).getAccountName());
        return userDto;
    }

    @Override
    public Boolean updateUser(Long id, UserDto userDto) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (!userMapper.exists(queryWrapper.eq(User::getId, id))) {
            throw new CustomException("该用户不存在");
        }

        queryWrapper.clear();
        if (userMapper.exists(queryWrapper.eq(User::getUsername, userDto.getUsername()).ne(User::getId, id))) {
            throw new CustomException("该用户已经存在");
        }

        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setId(id);
        return userMapper.updateById(user) == 1;
    }
}
